package com.vframework.system.user.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.annotation.JsonView;
import com.vframework.base.controller.BaseController;
import com.vframework.common.response.R;
import com.vframework.config.annotation.admin.AdminRestController;
import com.vframework.system.user.entity.SysUser;
import com.vframework.system.user.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2019-02-22
 */
@AdminRestController
@RequestMapping("/user")
@Api(tags = "用户管理")
public class SysUserController extends BaseController {

    @Autowired
    SysUserService userService;

    @GetMapping
    @PreAuthorize("hasAuthority('sys:user:list')")
    @JsonView(SysUser.UserSimpleView.class)
    @ApiOperation(value = "用户列表")
    public R<List<SysUser>> list() {
        return R.success(userService.list(new QueryWrapper<>()));
    }

    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('sys:user:query')")
    @JsonView(SysUser.UserSimpleView.class)
    @ApiOperation(value = "用户详情")
    public R<SysUser> query(@PathVariable Integer id) {
        SysUser sysUser = userService.getById(id);
        return R.success(sysUser);
    }

    @PostMapping("register")
    @PreAuthorize("hasAuthority('sys:user:add')")
    @JsonView(SysUser.UserSimpleView.class)
    @ApiOperation(value = "添加用户")
    public R<SysUser> register(@Valid @RequestBody SysUser sysUser, BindingResult errors) {
        if (errors.hasErrors()) {
            errors.getAllErrors().stream().forEach(error -> System.out.println(error.getDefaultMessage()));
            List<String> errorStr = errors.getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.toList());
            throw new RuntimeException(errorStr.toString());
        }
        sysUser.setPassword(new BCryptPasswordEncoder().encode(sysUser.getPassword()));
        sysUser.setStatus(SysUser.UserStatusEnum.VALID.getCode());
        userService.saveOrUpdate(sysUser, new LambdaUpdateWrapper<SysUser>().eq(SysUser::getUsername, sysUser.getUsername()));
        return R.success(sysUser);
    }

    @PostMapping("update")
    @PreAuthorize("hasAuthority('sys:user:update')")
    @JsonView(SysUser.UserSimpleView.class)
    @ApiOperation(value = "修改用户信息")
    public R<SysUser> update(@Valid @RequestBody SysUser sysUser, BindingResult errors) {
        if (errors.hasErrors()) {
            errors.getAllErrors().stream().forEach(error -> System.out.println(error.getDefaultMessage()));
            List<String> errorStr = errors.getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.toList());
            throw new RuntimeException(errorStr.toString());
        }
        if (BeanUtil.isEmpty(sysUser) || sysUser.getId() == null) {
            throw new RuntimeException("未查询到用户,修改失败");
        }
        if (StrUtil.isNotEmpty(sysUser.getPassword())) {
            sysUser.setPassword(new BCryptPasswordEncoder().encode(sysUser.getPassword()));
        }
        sysUser.setStatus(SysUser.UserStatusEnum.VALID.getCode());
        userService.updateById(sysUser);
        return R.success(sysUser);
    }
}
